package io.renren.modules.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import io.renren.common.constants.ExceptionConstants;
import io.renren.common.exception.BusinessRunTimeException;
import io.renren.common.utils.R;
import io.renren.modules.erp.entity.*;
import io.renren.modules.erp.service.AccountItemService;
import io.renren.modules.erp.vo.AccountItemVo4List;
import io.renren.modules.erp.vo.DepotHeadVo4List;
import io.renren.modules.sys.controller.AbstractController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ji sheng hua 752*718*920
 */
@RestController
@RequestMapping(value = "/accountItem")
public class AccountItemController  extends AbstractController {
    private Logger logger = LoggerFactory.getLogger(AccountItemController.class);

    @Resource
    private AccountItemService accountItemService;
    /**
     * create by: cjl
     * description:
     *  业务逻辑操作放在service层，controller只做参数解析和视图封装
     * create time: 2019/1/11 15:08
     * @Param: inserted
     * @Param: deleted
     * @Param: updated
     * @Param: headerId
     * @Param: listType
     * @Param: request
     * @return java.lang.String
     */
    @PostMapping(value = "/saveDetials")
    public R saveDetials( @RequestBody String beanJson,
                          HttpServletRequest request) throws Exception{
        JSONObject json = JSONObject.parseObject(beanJson);
        String inserted = json.getString("inserted");
        String deleted = json.getString("deleted");
        String updated = json.getString("updated");
        Long headerId = json.getLong("headerId");
        String listType = json.getString("listType");

        accountItemService.saveDetials(inserted,deleted,updated,headerId,listType,getUserId());
        return R.ok();
    }

    //根据accountId获取accountitem子表数据
    @GetMapping(value = "/getDetailList")
    public R getDetailList(@RequestParam("headerId") Long headerId,
                           HttpServletRequest request)throws Exception {
        List<AccountItemVo4List> dataList = new ArrayList<AccountItemVo4List>();
        if(headerId != 0) {
            dataList = accountItemService.getDetailList(headerId);
        }
        JSONObject outer = new JSONObject();
        outer.put("total", dataList.size());
        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        if (null != dataList) {
            for (AccountItemVo4List ai : dataList) {
                JSONObject item = new JSONObject();
                item.put("Id", ai.getId());
                item.put("AccountId", ai.getAccountId());
                item.put("AccountName", ai.getAccountName());
                item.put("InOutItemId", ai.getInOutItemId());
                item.put("InOutItemName", ai.getInOutItemName());
                BigDecimal eachAmount = ai.getEachAmount();
//                item.put("EachAmount", (eachAmount.compareTo(BigDecimal.ZERO))==-1 ? BigDecimal.ZERO.subtract(eachAmount): eachAmount);
                item.put("EachAmount", eachAmount);

                item.put("Remark", ai.getRemark());
                item.put("PaymentsType", ai.getPaymentsType());
                dataArray.add(item);
            }
        }
        List<DepotHeadVo> dataList2 = new ArrayList<>();
        dataList2 = accountItemService.getDetailList2(headerId);

        JSONArray dataArray2 = new JSONArray();
        if (null != dataList2) {
            for (DepotHeadVo a2 : dataList2) {
                JSONObject item = new JSONObject();
                item.put("operTimeStr", a2.getOperTime());
                item.put("defaultNumber", a2.getDefaultNumber());
                item.put("organName", a2.getOrganName());
                item.put("userName", a2.getUserName());
                item.put("payType", a2.getPayType());
                item.put("totalPrice", a2.getTotalPrice());
//                item.put("Remark", ai.getRemark());
                dataArray2.add(item);
            }
        }
        outer.put("rows", dataArray);
        outer.put("numbers", dataArray2);
        return R.ok().put("data",outer);
    }


    //根据accountId获取核销详情数据
    @GetMapping(value = "/getVerification")
    public R getVerification(@RequestParam("headerId") Long headerId,
                           HttpServletRequest request)throws Exception {
        List<AccountItemVo4List> dataList = new ArrayList<AccountItemVo4List>();
//        if(headerId != 0) {
//            dataList = accountItemService.getDetailList(headerId);
//        }
        JSONObject outer = new JSONObject();

        List<AccountHeadVo4ListEx> dataList2 = new ArrayList<>();
        dataList2 = accountItemService.getDetailList3(headerId);

        JSONArray dataArray2 = new JSONArray();
        if (null != dataList2) {
            for (AccountHeadVo4ListEx a2 : dataList2) {
                JSONObject item = new JSONObject();
                item.put("billTime", a2.getBillTime());
                item.put("billNo", a2.getBillNo());
                item.put("organName", a2.getOrganName());
                item.put("userName", a2.getUserName());
                item.put("sourceType", a2.getSourceType());
                //单据金额
                item.put("totalPrice", a2.getTotalPrice());
                //源单类型
                item.put("type", a2.getType());
                item.put("remark", a2.getRemark());

                dataArray2.add(item);
            }
        }
//        outer.put("rows", dataArray);
        outer.put("numbers", dataArray2);
        return R.ok().put("data",outer);
    }




    /**
     * create by: qiankunpingtai
     * website：https://qiankunpingtai.cn
     * description:
     *  批量删除财务明细信息
     * create time: 2019/3/29 10:56
     * @Param: ids
     * @return java.lang.Object
     */
    @RequestMapping(value = "/batchDeleteAccountItemByIds")
    public R batchDeleteAccountItemByIds(@RequestParam("ids") String ids) throws Exception {

        int i= accountItemService.batchDeleteAccountItemByIds(ids,getUserId());
        if(i<1){
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}]",
                    ExceptionConstants.ACCOUNT_ITEM_DELETE_FAILED_CODE,ExceptionConstants.ACCOUNT_ITEM_DELETE_FAILED_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.ACCOUNT_ITEM_DELETE_FAILED_CODE,
                    ExceptionConstants.ACCOUNT_ITEM_DELETE_FAILED_MSG);
        }
        return R.ok();
    }

    @PostMapping(value = "/add")
    public R insert(@RequestBody String beanJson, HttpServletRequest request) throws Exception{
        if(1==accountItemService.insertAccountItem(beanJson, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @PostMapping(value = "/update")
    public R update(@RequestBody String beanJson,@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
        if(1==accountItemService.updateAccountItem(beanJson, id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/delete")
    public R delete(@RequestParam("id") Long id, HttpServletRequest request)throws Exception {
        if(1==accountItemService.deleteAccountItem(id, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/batchDelete")
    public R batchDelete(@RequestParam("ids")String ids, HttpServletRequest request)throws Exception {
        if(1==accountItemService.batchDeleteAccountItem(ids, request)){
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/checkIsNameExist")
    public R checkIsNameExist(@RequestParam("id") Long id, @RequestParam("name") String name)throws Exception {
        if(0<accountItemService.checkIsNameExist(id, name)){
            return R.ok();
        }else{
            return R.error();
        }
    }

}
